package com.server;

import java.awt.event.KeyEvent;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;

public class ServerMain {

	public static void main(String[] args) throws Exception {

		int port = 12345;
		
		if (args.length == 1){
			try {
				port = Integer.valueOf(args[0]);
			} catch (Exception e) {
				System.out.println("Port error...");
				return;
			}
		}
		
		System.out.println("Server is listening at port:" + port + "...");
		
		ServerSocket serverSocket = new ServerSocket(port);
		
		while (true){
			Socket socket = serverSocket.accept();
			
			System.out.println("a client connected.");

			new Thread(new SocketThread(socket)).start();
		}
		
	}

}

class SocketThread implements Runnable{

	private Socket socket = null;
	
	public SocketThread(Socket socket) {
		this.socket = socket;
	}
	
	@Override
	public void run() {
		
		try {
			while (true){
				
				InputStream in = socket.getInputStream();
				OutputStream out = socket.getOutputStream();
				
				byte[] inBuf = new byte[1024];
				String serverSay = "";
				
				int i = 0;
				
				while (  (i = in.read(inBuf, 0, 1024)) != -1){
					serverSay += new String(inBuf, 0, i);
					if (inBuf[i-1] == KeyEvent.VK_ENTER)
						break;
				}
				
				if (serverSay.isEmpty()) break;
				
				System.out.print("Receive Message From("+ socket.getRemoteSocketAddress().toString() +"): " + serverSay);
				
				serverSay = "Server Say: " + serverSay;
				
				out.write(serverSay.getBytes());
			}
			
		} catch (Exception e) {
			System.out.println(e.getMessage());
		} finally {
			System.out.println("a client disconnected.");
		}
	}
	
}
	
